﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace S2_Xxxx_XxxNetApi
{
    public static class ListCommon
    {
        /// <summary>
        /// 判断List中是否有数据 返回true 表示有数据
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        public static Boolean HasData<T>(this List<T> lst)
        {
            Boolean result = false;
            if (lst != null && lst.Count > 0)
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 判断IEnumerable中是否有数据 返回true 表示有数据
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        public static Boolean HasData<T>(this IEnumerable<T> lst)
        {
            Boolean result = false;
            if (lst != null && lst.Count() > 0)
            {
                result = true;
            }
            return result;
        }

        public static string Join(this List<string> list, string s)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in list)
            {
                sb.AppendFormat("{0}{1}", item, s);
            }
            if (sb.Length != 0)
            {
                sb.Length -= s.Length;
            }
            return sb.ToString();
        }
        //将数据转换成DataTable
        public static DataTable ToDataTable<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
            var t = new DataTable();

            elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
            foreach (T item in list)
            {
                var row = t.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                t.Rows.Add(row);
            }
            return t;
        }
    }
}
